import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { RootState } from '@/types/store';
import { Action, ThunkAction } from '@reduxjs/toolkit';
import { useEffect } from 'react';

// 自定义hook          参数：thunkaction的名称，redux的状态
const useInitialState = <StateName extends keyof RootState>(
  action: () => ThunkAction<void, RootState, unknown, Action>,
  stateName: StateName
) => {
  // 分发异步action
  const dispatch = useAppDispatch();
  //   获取redux状态
  const state = useAppSelector((state) => state[stateName]);

  //   在点击页面第一时间获取渲染  要useeffect里分发dispatch，action是参数传过来的
  useEffect(() => {
    dispatch(action());
  }, [dispatch, action]);

  return state;
};

export { useInitialState };
